package com.tanhua.api.impl.db;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.api.db.SoulQuestionApi;
import com.tanhua.domain.db.SoulQuestion;
import com.tanhua.mapper.db.SoulQuestionMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author Richard Wang
 * @date 2021/9/5 15:11
 */
@Service
public class SoulQuestionApiImpl implements SoulQuestionApi {

    @Autowired
    private SoulQuestionMapper soulQuestionMapper;
    @Override
    public Integer findPaperId(Integer questionId) {
        QueryWrapper<SoulQuestion> qr = new QueryWrapper<>();
        qr.eq("id",questionId);
       // SoulQuestion soulQuestion = soulQuestionMapper.selectOne(qr);
        List<SoulQuestion> list = soulQuestionMapper.selectList(qr);
        //所有试题的所属试卷是一样的,故只要一个即可
        SoulQuestion soulQuestion = list.get(0);
        return soulQuestion.getQuestionLevel();
    }


    /**
     * 分页查询灵魂问题列表
     *
     * @param pageNum  当前页
     * @param pageSize 页大小
     * @return
     */
    @Override
    public IPage findByPage(Integer pageNum, Integer pageSize, Integer levelId, String keyword) {
        Page<SoulQuestion> pg = new Page<>(pageNum, pageSize);

        QueryWrapper<SoulQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("updated");
        if (levelId != null) {
            queryWrapper.eq("question_level", levelId);
        }

        if (!"".equals(keyword)) {
            queryWrapper.like("question", "%" + keyword +"%");
        }

        return soulQuestionMapper.selectPage(pg, queryWrapper);
    }

    /**
     * 添加问题
     * @param soulQuestion
     */
    @Override
    public Integer save(SoulQuestion soulQuestion) {
        soulQuestionMapper.insert(soulQuestion);

        return soulQuestion.getId();
    }

    @Override
    public SoulQuestion findById(Integer id) {

        QueryWrapper<SoulQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);

        return soulQuestionMapper.selectOne(queryWrapper);
    }


    /**
     * 更新问题
     * @param soulQuestion
     */
    @Override
    public void update(SoulQuestion soulQuestion) {
        soulQuestionMapper.updateById(soulQuestion);
    }


    /**
     * 根据 id 删除
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        soulQuestionMapper.deleteById(id);
    }
}
